package com.ft.common.json;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Map;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ft.common.utils.text.StringUtils;

/**
 * json对象辅助类
 * @author mdc mdc@comit.com.cn
 * maidachao comit
 * -ft-
 */
public class JsonHelper {
	public static final String defaultFormat = "yyyy-MM-dd HH:mm:ss";
	/**
	 * 据说json==>对象是线程安全的
	 */
	public static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

	public static <T> T parseToObject(InputStream is, Class<T> toClass) {
		try {
			
			OBJECT_MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,false);
			
			return (T) OBJECT_MAPPER.readValue(is, toClass);
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}

	public static <T> T parseToObject(byte[] b, int offset, int len, Class<T> valueType) {
		try {
			return (T) OBJECT_MAPPER.readValue(b, offset, len, valueType);
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}

	public static <T> T parseToObject(String json, Class<T> toClass) {
		try {
			if (StringUtils.isNullOrEmpty(json)) {
				return null;
			}
			return (T) OBJECT_MAPPER.readValue(json, toClass);
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}

	public static Map parseToMap(String json) {
		return parseToObject(json, Map.class);
	}

	public static Map parseToMap(byte[] b) {
		if (b == null || b.length == 0) {
			return null;
		}
		return parseToObject(b, 0, b.length, Map.class);
	}

	public static Map parseToMap(InputStream is) {
		return parseToObject(is, Map.class);
	}

	public static String parseToJson(Object o,String dfm) {
		if (o == null) {
			return null;
		}
		try {
			SimpleDateFormat dateFormat = null;
			if(dfm == null){
				dateFormat = new SimpleDateFormat(defaultFormat);
			}else{
				dateFormat = new SimpleDateFormat(dfm);
			}
			OBJECT_MAPPER.setDateFormat(dateFormat);
			return OBJECT_MAPPER.writeValueAsString(o);
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}
	
	public static String parseToJson(Object o){
		if (o == null) {
			return null;
		}
		try {
			return OBJECT_MAPPER.writeValueAsString(o);
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}
	
	 /**
     * map  转JavaBean
     */
    public static <T> T map2pojo(Map<String,Object> obj, Class<T> clazz) {
        return OBJECT_MAPPER.convertValue(obj, clazz);
    }

	
}
